﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using S7.Net;

namespace DataCollector
{
    public class CollectorDriver
    {
        Plc plc1;
        // 连接PLC
        public void ConnectPlc()
        {
            // 创建PLC连接对象, ip为界面IP输入框的内容, rack和slot采用默认值0(具体值可以参考西门子PLC相关文档)
            plc1?.Close();
            plc1 = new Plc(CpuType.S71200, "192.168.1.102", 0, 0);
            try
            {
                // 打开与PLC的连接
                plc1.Open();                                  
            }
            catch (Exception)
            {
                Console.WriteLine("PLC连接失败");
            }

            SendHeartBeatThread();
        }


        private void SendHeartBeatThread()
        {

            Task.Run(() =>
            {
                while (true)
                {
                    // PLC连接状态为已连接时进入
                    if (plc1 != null && plc1.IsConnected)
                    {
                        try
                        {
                            // 下发心跳
                            Console.WriteLine(plc1.Read("DB5.DBW2").ToString());
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("重新连接PLC" + ex.Message);
                            // 再次连接PLC
                            ConnectPlc();
                        }
                    }
                    // PLC连接状态为未连接时进入
                    else if (plc1 != null && !plc1.IsConnected)
                    {
                        Console.WriteLine("重新连接PLC");
                        // 再次连接PLC
                        ConnectPlc();
                    }
                    // 加延时,具体延时多长时间,根据下位机要求来做
                    Thread.Sleep(plc1.IsConnected?2000:10);
                }
            });

        }

    }
}
